<template>
  <div class="flex flex-col h-full overflow-hidden">
    <app-header/>

    <main class="flex items-center justify-center p-6">
      <div
        class="confirm-card bg-[var(--bg-secondary)] rounded-lg shadow-md p-8 border border-[var(--border-color)] text-center max-w-sm w-full">
        <div class="warning-icon mb-4 text-4xl text-[var(--status-red)]">
          <i class="fas fa-exclamation-triangle"></i>
        </div>
        <h2 class="card-title text-lg font-bold text-[var(--text-primary)] mb-4">确认删除报警地址组</h2>
        <p class="confirm-message text-[var(--text-secondary)] mb-6">
          您确定要删除报警地址组 "<strong class="text-red-500">{{ addressNameToDelete }}</strong>" 吗？此操作不可撤销。
        </p>

        <div class="button-group flex justify-center gap-4">
          <button type="button" id="btn-cancel-delete"
                  class="hmi-button hmi-button-secondary px-6 py-2 rounded-md text-base font-semibold" @click="goBack">
            <i class="fas fa-times"></i>取消
          </button>
          <button type="button" id="btn-confirm-delete"
                  class="hmi-button hmi-button-danger px-6 py-2 rounded-md text-base font-semibold"
                  @click="confirmDeleteAlarmGroup" :disabled="isDeleting">
            <i :class="isDeleting ? 'fas fa-spinner fa-spin' : 'fas fa-check'"></i>{{
              isDeleting ? '删除中...' : '确认删除'
            }}
          </button>
        </div>
      </div>
    </main>

    <div v-if="notification.show" id="notification" class="notification"
         :class="{ 'notification-success': notification.type === 'success', 'notification-error': notification.type === 'error', 'show': notification.show }">
      <span id="notification-message">{{ notification.message }}</span>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, onUnmounted} from 'vue' // 导入 onUnmounted
import {useRouter, useRoute} from 'vue-router' // 导入 useRouter, useRoute
// 不再需要导入 AppHeader，因为它已全局配置

const router = useRouter() // 获取路由实例
const route = useRoute() // 获取当前路由信息

// --- 响应式数据 ---
const groupIdToDelete = ref(null)
const addressNameToDelete = ref('')
const isDeleting = ref(false) // 用于控制删除按钮的加载状态

// 通知状态
const notification = reactive({
  show: false,
  message: '',
  type: 'success', // 'success' or 'error'
  timeoutId: null // 用于存储定时器ID
})


// --- 方法 ---

// 显示通知
const showNotification = (message, type = 'success') => {
  notification.show = true
  notification.message = message
  notification.type = type
  if (notification.timeoutId) {
    clearTimeout(notification.timeoutId)
  }
  notification.timeoutId = setTimeout(() => {
    notification.show = false
  }, 3000)
}

// 从路由参数获取地址组 ID 和地址名称
const getAlarmGroupInfoFromRoute = () => {
  // 假设地址组 ID 从路由 params 获取，地址名称从 query 获取 (或者都从 query)
  // 请根据你的实际路由配置调整这里
  groupIdToDelete.value = route.params.id || route.query.id
  addressNameToDelete.value = route.query.address || '该报警地址组' // Default text if address is not available

  if (!groupIdToDelete.value) {
    console.error('Error: Alarm group ID not found in route parameters.')
    showNotification('无法确定要删除的报警地址组 ID。', 'error')
    // 延迟导航回列表页
    setTimeout(() => {
      router.replace('/settings/alarm-config') // 假设报警地址组列表页路由
    }, 1000)
  }
}


// 确认删除报警地址组
const confirmDeleteAlarmGroup = async () => {
  if (!groupIdToDelete.value) {
    showNotification('错误：无法确定要删除的报警地址组 ID。', 'error');
    return;
  }

  isDeleting.value = true; // 显示删除中状态

  try {
    let result = { success: false, error: '未知错误' };
    
    if (window.electronAPI && window.electronAPI.alarmGroups) {
      // 使用Electron API删除
      result = await window.electronAPI.alarmGroups.delete(groupIdToDelete.value);
    } else {
      console.warn('未检测到Electron API，模拟删除操作');
      // 模拟删除成功 (开发环境)
      await new Promise(resolve => setTimeout(resolve, 1000));
      result = { success: true };
    }

    if (result.success) {
      showNotification(`报警地址组 "${addressNameToDelete.value}" 删除成功!`, 'success');
      // 删除成功后导航回列表页
      setTimeout(() => {
        router.push('/settings/alarm-config');
      }, 500);
    } else {
      throw new Error(result.error || '删除失败');
    }
  } catch (error) {
    console.error('删除报警地址组失败:', error);
    showNotification(`删除失败: ${error.message}`, 'error');
  } finally {
    isDeleting.value = false; // 隐藏删除中状态
  }
};

// 导航回报警地址组列表页面 (取消删除)
const goBack = () => {
  // 直接返回报警地址组列表页面
  router.back()// 假设报警地址组列表页路由是 /settings/alarm-config
}


// --- 生命周期钩子 ---
onMounted(() => {
  console.log('Alarm Group Delete Confirm Page mounted')
  // 页面挂载后从路由获取地址组 ID 和地址名称
  getAlarmGroupInfoFromRoute()
})

// 导入了 onUnmounted，即使此处模拟代码没有显式使用，也符合您的要求
onUnmounted(() => {
  console.log('Alarm Group Delete Confirm Page unmounted')
  // 清理通知定时器
  if (notification.timeoutId) {
    clearTimeout(notification.timeoutId)
  }
})

// ESC键返回功能
onMounted(() => {
  const handleEscape = (event) => {
    if (event.key === 'Escape') {
      // 触发与取消按钮相同的逻辑
      goBack()
    }
  }
  document.addEventListener('keydown', handleEscape)
  onUnmounted(() => {
    document.removeEventListener('keydown', handleEscape)
  })
})

</script>

<style scoped>
/* --- 将原始 HTML 文件中的所有自定义样式复制到这里 --- */

/* --- Inherited Styles & Color Palette --- */
/* 根变量通常在全局 CSS 中定义，但为了完整性，这里列出 */
/* :root {
  --bg-primary: #f3f4f6;
  --bg-secondary: #ffffff;
  --text-primary: #1f2937;
  --text-secondary: #6b7280;
  --text-tertiary: #9ca3af;
  --border-color: #e5e7eb;
  --accent-blue: #3b82f6;
  --status-green: #22c55e;
  --status-yellow: #eab308;
--status-gray: #6b7280

;
--status-off: #9ca3af

;
--online-green: #10b981

;
--offline-red: #f43f5e

;
}
*

/

/* body 样式通常由父组件或全局 App.vue 控制 */
/* body {
  font-family: 'Inter', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  background-color: var(--bg-primary);
  color: var(--text-primary);
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  overflow: hidden;
  margin: 0;
  padding: 0;
} */


/* --- Header (Consistent) --- */
/* Header 样式已移至 AppHeader.vue 或全局 */


/* --- Main Content Area --- */
/* main flex alignment handled by Tailwind classes */
main {
  flex-grow: 1;
  /* padding: 1.5rem; Not needed here due to flex centering */
  overflow-y: auto;
}

/* --- Confirmation Card --- */
.confirm-card {
  background-color: var(--bg-secondary);
  border-radius: 0.5rem; /* rounded-lg */
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1); /* shadow-md */
  padding: 2rem; /* p-8 */
  border: 1px solid var(--border-color);
  text-align: center;
  max-width: 400px; /* max-w-sm */
  width: 100%; /* w-full */
}

.warning-icon {
  font-size: 2.5rem; /* text-4xl */
  color: var(--status-red);
  margin-bottom: 1rem; /* mb-4 */
}

.card-title {
  font-size: 1.125rem; /* text-lg */
  font-weight: 700; /* font-bold */
  color: var(--text-primary);
  margin-bottom: 1rem; /* mb-4 */
}

.confirm-message {
  color: var(--text-secondary);
  margin-bottom: 1.5rem; /* mb-6 */
  line-height: 1.5;
}

.confirm-message strong {
  color: var(--status-red); /* text-red-500 */
}

/* --- Buttons (Common Styles) --- */
.button-group {
  display: flex;
  gap: 1rem;
  justify-content: center;
}

.hmi-button {
  padding: 0.6rem 1.2rem;
  border-radius: 0.375rem; /* rounded-md */
  font-size: 1rem; /* text-base */
  font-weight: 600;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 0.4rem;
  border: 1px solid transparent;
  transition: all 0.2s ease;
  cursor: pointer;
}

/* Adjusted padding for small button */
.hmi-button-small {
  padding: 0.35rem 0.7rem;
  font-size: 0.75rem;
}

.hmi-button i {
  font-size: 1em;
}

/* HMI Button Colors - Defined by variables */
.hmi-button-primary {
  background-color: var(--accent-blue);
  color: white;
  border-color: var(--accent-blue);
}

.hmi-button-primary:hover {
  background-color: #2563eb;
  border-color: #2563eb;
}

/* Specific hover color */
.hmi-button-secondary {
  background-color: var(--bg-secondary);
  color: var(--text-primary);
  border-color: var(--border-color);
}

.hmi-button-secondary:hover {
  background-color: #f9fafb;
  border-color: #d1d5db;
}

/* Specific hover color */
.hmi-button-danger {
  background-color: var(--status-red);
  color: white;
  border-color: var(--status-red);
}

.hmi-button-danger:hover {
  background-color: #dc2626;
  border-color: #dc2626;
}

.hmi-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}


/* --- Notification (Common Styles) --- */
.notification {
  position: fixed;
  bottom: 1rem;
  left: 50%;
  transform: translateX(-50%);
  padding: 0.75rem 1.25rem;
  border-radius: 0.5rem;
  color: white;
  font-size: 0.875rem;
  font-weight: 500;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.3s ease, visibility 0.3s ease;
  z-index: 100;
}

.notification.show {
  opacity: 1;
  visibility: visible;
}

/* Notification Colors - Defined by variables */
.notification-success {
  background-color: var(--status-green);
}

.notification-error {
  background-color: var(--status-red);
}


/* Body styles from original inline style */
/* max-width: 800px; max-height: 600px; margin: auto; */
/* These should ideally be managed in a layout component or App.vue */

</style>
